package com.xdap.init.dao;

import com.definesys.mpaas.query.MpaasQuery;
import com.xdap.motor.utils.StringUtils;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@RequiredArgsConstructor
public class InitSelectDao {
    private final RuntimeDatasourceService runtimeDatasourceService;

    @Value("${spring.datasource.name}")
    private String tenantSchema;

    public List<String> getIds(String tableName, String fieldName, Object fieldData) {
        if (fieldData == null || StringUtils.isBlank(fieldData + "")) {
            return null;
        }
        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(tenantSchema);
        mpaasQuery.select("id");
        String fieldDataStr = fieldData + "";
        if (fieldDataStr.contains(",")) {
            String[] fieldDataList = fieldDataStr.split(",");
            mpaasQuery.in(fieldName, fieldDataList);
        } else {
            mpaasQuery.eq(fieldName, fieldData);
        }
        mpaasQuery.table(tableName);
        List<String> ids = mpaasQuery.doQuery(String.class);
        return ids;
    }

}
